<template>
	<view class="wallet-container">
		<!-- 顶部导航 -->
		<view class="wallet-header">
			<view class="back-btn" @click="goBack">
				<i class="iconfont icon-arrow-left"></i>
			</view>
			<view class="header-title">钱包充值</view>
		</view>

		<!-- 余额显示区域 -->
		<view class="balance-card">
			<view class="balance-title">当前余额</view>
			<view class="balance-amount">¥{{ balance }}</view>
			<view class="balance-hint">上次充值: {{ lastRechargeTime }}</view>
		</view>

		<!-- 充值金额选择 -->
		<view class="amount-section">
			<view class="section-title">充值金额</view>
			<view class="amount-grid">
				<view v-for="amount in presetAmounts" :key="amount"
					:class="['amount-item', selectedAmount === amount ? 'active' : '']" @click="selectAmount(amount)">
					¥{{ amount }}
				</view>
				<view class="amount-item custom-amount" @click="showCustomInput = true">
					<view v-if="!showCustomInput">
						<i class="iconfont icon-plus"></i>
						<text>自定义</text>
					</view>
					<view v-else class="custom-input-wrapper">
						<input v-model="customAmount" type="digit" placeholder="输入金额" 
							@confirm="handleCustomAmount" 
							@blur="handleCustomInputBlur"
							class="custom-input"
							focus>
						<text class="yuan">元</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 支付方式选择 -->
		<view class="payment-section">
			<view class="section-title">支付方式</view>
			<view class="payment-list">
				<view v-for="payment in paymentMethods" :key="payment.value"
					:class="['payment-item', selectedPayment === payment.value ? 'active' : '']"
					@click="selectPayment(payment.value)">
					<image :src="payment.icon" mode="widthFix" class="payment-icon"></image>
					<view class="payment-name">{{ payment.name }}</view>
					<view class="payment-check">
						<i class="iconfont icon-check" v-show="selectedPayment === payment.value"></i>
					</view>
				</view>
			</view>
		</view>

		<!-- 充值按钮 -->
		<view class="recharge-btn-container">
			<button class="recharge-btn" :disabled="!canRecharge" @click="handleRecharge">
				{{ buttonText }}
			</button>
		</view>

		<!-- 充值提示 -->
		<view class="recharge-tips">
			<view class="tip-item">
				<i class="iconfont icon-info"></i>
				<text>充值金额将实时到账，支持7*24小时服务</text>
			</view>
			<view class="tip-item">
				<i class="iconfont icon-info"></i>
				<text>如有疑问，请联系在线客服</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		findMoney,
		chargeMoney
	} from '@/api/wallet.js';
	
	// 数据状态
	const balance = ref('0.00'); // 钱包余额
	const lastRechargeTime = ref('--'); // 上次充值时间
	const presetAmounts = ref([10, 20, 50, 100, 200, 500]); // 预设充值金额
	const selectedAmount = ref(''); // 选中的充值金额
	const customAmount = ref(''); // 自定义金额
	const showCustomInput = ref(false); // 是否显示自定义输入框

	// 支付方式
	const paymentMethods = ref([{
			value: 'wechat',
			name: '微信支付',
			icon: '/static/icons/pay-wechat.png'
		},
		{
			value: 'alipay',
			name: '支付宝',
			icon: '/static/icons/pay-alipay.png'
		},
		{
			value: 'card',
			name: '银行卡',
			icon: '/static/icons/pay-card.png'
		}
	]);
	const selectedPayment = ref('wechat'); // 默认选中微信支付
	
	// 计算属性
	const canRecharge = computed(() => {
		return selectedAmount.value && parseFloat(selectedAmount.value) > 0;
	});
	
	const buttonText = computed(() => {
		if (!selectedAmount.value) return '请选择金额';
		return `确认充值 ¥${selectedAmount.value}`;
	});

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 选择预设金额
	const selectAmount = (amount) => {
		selectedAmount.value = amount;
		showCustomInput.value = false;
		customAmount.value = '';
	};

	// 处理自定义金额输入框失焦
	const handleCustomInputBlur = () => {
		if (customAmount.value) {
			handleCustomAmount();
		} else {
			showCustomInput.value = false;
		}
	};

	// 处理自定义金额
	const handleCustomAmount = () => {
	  if (customAmount.value) {
	    const amount = parseFloat(customAmount.value);
	    if (!isNaN(amount)) { // 这里添加了缺失的右括号
	      // 限制最小充值金额为0.01元
	      if (amount < 0.01) {
	        uni.showToast({
	          title: '充值金额不能小于0.01元',
	          icon: 'none'
	        });
	        return;
	      }
	      
	      // 限制最大充值金额为10000元
	      if (amount > 10000) {
	        uni.showToast({
	          title: '单次充值不能超过10000元',
	          icon: 'none'
	        });
	        return;
	      }
	      
	      // 保留两位小数
	      selectedAmount.value = amount.toFixed(2);
	      showCustomInput.value = false;
	    } else {
	      uni.showToast({
	        title: '请输入有效的金额',
	        icon: 'none'
	      });
	    }
	  }
	};

	// 选择支付方式
	const selectPayment = (payment) => {
		selectedPayment.value = payment;
	};

	// 余额充值
	const handleRecharge = async () => {
	  if (!canRecharge.value) {
	    uni.showToast({
	      title: '请选择充值金额',
	      icon: 'none'
	    });
	    return;
	  }
	
	  // 显示确认对话框
	  uni.showModal({
	    title: '确认充值',
	    content: `您将充值 ¥${selectedAmount.value} 到账户，使用${getPaymentName()}支付`,
	    success: async (res) => {
	      if (res.confirm) {
	        // 显示加载状态
	        uni.showLoading({
	          title: '充值中...',
			  mask: true
	        });
	
	        	        // 获取userId（从登录状态获取）
	        const userId = uni.getStorageSync("userId");
	        if (!userId) {
	          uni.hideLoading();
	          uni.showToast({
	            title: '请先登录',
	            icon: 'none',
	            duration: 2000
	          });
	          return;
	        }

	        try {
	          // 调用充值API
	          const user = {
	            userId: userId,
	            wallet: parseFloat(selectedAmount.value) // 确保传入数值类型
	          }
	          
	          console.log('充值参数:', user);
	          const chargeResult = await chargeMoney(user);
	          console.log('充值结果:', chargeResult);
	          
	          // 充值成功，刷新余额
	          await findMoneyByUserId();
	          
	          uni.hideLoading();
	          uni.showToast({
	            title: '充值成功',
	            icon: 'success',
				duration: 2000
	          });
	          
	          // 更新最后充值时间
	          lastRechargeTime.value = getCurrentTime();
	          
	          // 重置选择
	          selectedAmount.value = '';
	          customAmount.value = '';
	          
	          // 通知其他页面更新数据
	          uni.$emit('userStatsUpdated');
	          
	          // 3秒后返回上一页
	          setTimeout(() => {
				  uni.navigateBack();
			  }, 2000);
	          
	        } catch (error) {
	          console.error("充值异常:", error);
	          uni.hideLoading();
	          uni.showToast({
	            title: error.message || "充值失败，请重试",
	            icon: "none"
	          });
	        }
	      }
	    }
	  });
	};

	// 获取支付方式名称
	const getPaymentName = () => {
		const payment = paymentMethods.value.find(item => item.value === selectedPayment.value);
		return payment ? payment.name : '';
	};

	// 获取当前时间
	const getCurrentTime = () => {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		const day = String(now.getDate()).padStart(2, '0');
		const hour = String(now.getHours()).padStart(2, '0');
		const minute = String(now.getMinutes()).padStart(2, '0');
		return `${year}-${month}-${day} ${hour}:${minute}`;
	};

	// 根据userId查询余额
	const findMoneyByUserId = async () => {
		try {
			const userId = uni.getStorageSync("userId");
			if (!userId) {
				console.warn('未找到用户ID，无法获取余额');
				uni.showToast({
					title: '请先登录',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			const params = { userId: userId };
			console.log('查询余额，用户ID:', userId);
			const res = await findMoney(params);
			console.log('余额查询响应:', res);
			
			// 格式化余额为两位小数
			if (res.data !== null && res.data !== undefined) {
				const money = parseFloat(res.data);
				balance.value = isNaN(money) ? '0.00' : money.toFixed(2);
			} else {
				balance.value = '0.00';
			}
		} catch (error) {
			console.error("获取余额异常:", error);
			uni.showToast({
				title: error.message || "获取余额失败",
				icon: "none"
			});
		}
	};
	
	// 页面加载时获取余额
	onMounted(() => {
		findMoneyByUserId();
	});
</script>

<style scoped>
	.wallet-container {
		padding: 30rpx;
		background-color: #f5f5f5;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 顶部导航 */
	.wallet-header {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		background-color: white;
		position: relative;
		border-radius: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 30rpx;
	}

	.back-btn {
		position: absolute;
		left: 30rpx;
		font-size: 40rpx;
		color: #333;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}

	/* 余额卡片 */
	.balance-card {
		background: linear-gradient(135deg, #4776E6, #8E54E9);
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 30rpx;
		color: white;
		box-shadow: 0 10rpx 20rpx rgba(71, 118, 230, 0.3);
	}

	.balance-title {
		font-size: 28rpx;
		margin-bottom: 10rpx;
		opacity: 0.8;
	}

	.balance-amount {
		font-size: 60rpx;
		font-weight: 700;
		margin-bottom: 20rpx;
	}

	.balance-hint {
		font-size: 24rpx;
		opacity: 0.8;
	}

	/* 充值金额选择 */
	.amount-section {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 30rpx;
		font-weight: 600;
	}

	.amount-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
	}

	.amount-item {
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f8f8;
		border-radius: 16rpx;
		font-size: 30rpx;
		color: #666;
		transition: all 0.3s ease;
	}

	.amount-item.active {
		background: linear-gradient(135deg, #4776E6, #8E54E9);
		color: white;
		box-shadow: 0 4rpx 15rpx rgba(71, 118, 230, 0.3);
		transform: translateY(-2rpx);
	}

	.custom-amount {
		position: relative;
	}

	.custom-input-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		padding: 0 20rpx;
	}

	.custom-input {
		width: 120rpx;
		height: 60rpx;
		font-size: 30rpx;
		text-align: center;
		border-bottom: 2rpx solid #4776E6;
		margin-right: 10rpx;
	}

	.yuan {
		font-size: 28rpx;
		color: #333;
	}

	/* 支付方式选择 */
	.payment-section {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 60rpx;
		box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
	}

	.payment-list {
		display: flex;
		flex-direction: column;
	}

	.payment-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		position: relative;
	}

	.payment-item:last-child {
		border-bottom: none;
	}

	.payment-item.active {
		color: #4776E6;
	}

	.payment-icon {
		width: 50rpx;
		height: 50rpx;
		margin-right: 20rpx;
	}

	.payment-name {
		font-size: 28rpx;
		flex: 1;
	}

	.payment-check {
		font-size: 30rpx;
		color: #4776E6;
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.payment-item.active .payment-check {
		opacity: 1;
	}

	/* 充值按钮 */
	.recharge-btn-container {
		margin-bottom: 30rpx;
	}

	.recharge-btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(135deg, #FF7D00, #FFA500);
		color: white;
		font-size: 32rpx;
		font-weight: 600;
		border-radius: 45rpx;
		box-shadow: 0 6rpx 20rpx rgba(255, 125, 0, 0.3);
		padding: 0;
		border: none;
		transition: all 0.3s;
	}

	.recharge-btn:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 10rpx rgba(255, 125, 0, 0.3);
	}

	.recharge-btn:disabled {
		background: #cccccc;
		box-shadow: none;
		transform: none;
	}

	/* 充值提示 */
	.recharge-tips {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		padding-bottom: 40rpx;
	}

	.tip-item {
		display: flex;
		align-items: center;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	.tip-item i {
		margin-right: 10rpx;
		font-size: 24rpx;
		color: #4776E6;
	}
</style>